package com.yuedou.api.controller.product;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yuedou.api.constant.ResponseCode;
import com.yuedou.api.controller.platform.BaseController;
import com.yuedou.api.entity.mer.*;
import com.yuedou.api.entity.platform.AdBanner;
import com.yuedou.api.entity.platform.SplitAccount;
import com.yuedou.api.entity.product.*;
import com.yuedou.api.entity.wxmsg.WxTemplate;
import com.yuedou.api.entity.wxuser.*;
import com.yuedou.api.pay.wxpay.WxAppPay;
import com.yuedou.api.service.mer.*;
import com.yuedou.api.service.platfom.*;
import com.yuedou.api.service.product.*;
import com.yuedou.api.service.wxuser.UserAddressService;
import com.yuedou.api.service.wxuser.UserService;

import com.yuedou.api.websocket.WebSocketServer;
import com.vdurmont.emoji.EmojiParser;
import com.yuedou.api.util.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

/**
 *@Author: ZhouWei
 *@Description:  商品订单相关接口
 *@Date 2025-01-17
 */
@Component
@RestController
@RequestMapping("/product/order")//url:模块/资源/{}/细分
public class ProductOrderController extends BaseController {

    @Resource
    private ProductOrderService productOrderService;
    @Resource
    private ProductOrderInfoService productOrderInfoService;
    @Resource
    private ProductService productService;
    @Resource
    private ProductCartService productCartService;
    @Resource
    private UserService userService;
    @Resource
    private MerService merService;
    @Resource
    private MerUserService merUserService;
    @Resource
    private UserAddressService userAddressService;
    @Resource
    private AdBannerService adBannerService;
    @Resource
    private ProductAttrValueService productAttrValueService;
    @Resource
    private ProductOrderRefundImgService orderRefundImgService;
    @Resource
    private SplitAccountService splitAccountService;
    @Resource
    private WxTemplateService wxTemplateService;


    @Value("${web.imgPrefix}")
    private String imgPrefix;//图片地址
    @Value("${web.uploadPath}")
    private String uploadPath;//图片地址


    /** 通过购物车生成订单
     * @param
     * @throws Exception
     */
    @PostMapping(value="/test")
    public JSONObject test(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "product/order/addOrder 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int order_id = jsonRequest.containsKey("order_id") ? jsonRequest.getInt("order_id") : 0;
//            2795
            ProductOrder order = productOrderService.findById(order_id);
            if(order!=null){
//                productOrderService.buyDeviceUpdate(order);
//                ProductOrderInfo orderInfo = productOrderInfoService.findById(195);
//                productOrderService.splitMoneyByInfo(order, orderInfo);
            }

//            MallGroupOpenList openList = mallGroupOpenListService.findById(16);
////
////            mallGroupOpenListService.refundOpenList(openList);
////            ProductOrder order, MallGroupProduct groupProduct, MallGroupOpenList openList
//            User user = userService.findById(1);
//            MallGroupProduct groupProduct = groupProductService.findById(1);
//            wxTemplateService.sendWxSubMsgOpenGroupSuccess(user,order,groupProduct,openList);
//

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功"),true,true);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
            System.out.println(""+e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 获取所有订单列表
     * @param
     * @throws Exception
     */
    @PostMapping(value="/list")
    public JSONObject getList(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "product/order/list 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int state = jsonRequest.containsKey("state") ? jsonRequest.getInt("state") : 1;
            int order_type = jsonRequest.containsKey("order_type") ? jsonRequest.getInt("order_type") : 0;
            // 0 - 普通用户查看列表  1 - 管理员 查看列表
            int from_type = jsonRequest.containsKey("from_type") ? jsonRequest.getInt("from_type") : 0;
            int pageIndex = jsonRequest.containsKey("pageIndex") ? jsonRequest.getInt("pageIndex") : 1;
            int pageSize = jsonRequest.containsKey("pageSize") ? jsonRequest.getInt("pageSize") : 10;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户信息不存在"),true,true);
            }

            //订单状态 0 - 未支付  1 - 支付中  2 - 已支付 3 - 待发货  4 - 已发货 待收货  5 - 已完成收货待评价 6 - 已评价（已完成）
            List<ProductOrder> list = productOrderService.queryListByUserId(user_id,order_type,state,pageIndex,pageSize);

            //广告的类型  1 - 个人中心处广告  2 - 订单列表处广告 3 - 优惠券列表处广告
            AdBanner banner = adBannerService.getBannerByAdType(2);
            map.put("orders",list);
            map.put("banner",banner);
            if(banner != null){
                map.put("hasBanner",1);
            }else{
                map.put("hasBanner",0);
            }
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",list.size(), map),false,false);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
            System.out.println(""+e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 获取商家所有订单列表
     * @param
     * @throws Exception
     */
    @PostMapping(value="/mer/list")
    public JSONObject getMerList(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "product/order/mer/list 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int mer_id = jsonRequest.containsKey("mer_id") ? jsonRequest.getInt("mer_id") : 0;
            int state = jsonRequest.containsKey("state") ? jsonRequest.getInt("state") : 2;
            int pageIndex = jsonRequest.containsKey("pageIndex") ? jsonRequest.getInt("pageIndex") : 1;
            int pageSize = jsonRequest.containsKey("pageSize") ? jsonRequest.getInt("pageSize") : 10;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户信息不存在"),true,true);
            }

            MerUser merUser = merUserService.getMerUser(user_id);
            if(merUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您不是商家管理员"),true,true);
            }

            Mer mer = merService.findById(mer_id);
            if(mer == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您不是商家管理员"),true,true);
            }

            //订单状态订单状态 0 - 未支付   1 - 支付中  2 - 已支付（待核销）  3 - 已核销  4 - 已评价  5 - 订单取消  6 - 发起退货  7 - 同意退货  8 - 退货完成  9 - 拒绝退货
            List<ProductOrder> list = productOrderService.queryListByMerId(mer_id,state,pageIndex,pageSize);

            map.put("orders",list);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",list.size(), map),false,false);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    /**
     *  商家查看订单详情
     * @param
     * @throws Exception
     */
    @PostMapping(value="/detailByMer")
    public JSONObject detailByMer(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int order_id = jsonRequest.containsKey("order_id") ? jsonRequest.getInt("order_id") : 0;
//            int mer_id = jsonRequest.containsKey("mer_id") ? jsonRequest.getInt("mer_id") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            ProductOrder order = productOrderService.getOrderDetail(order_id);
            if(order == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前订单不存在"),true,true);
            }

//            MerUser merUser = merUserService.getMerUser(user_id);
//            if(merUser == null || order.getUserId().intValue() != user_id){
//                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您没有该权限" ),true,true);
//            }

            map.put("order",order);
            map.put("allPrice", MathUtil.getDoubleUp(order.getPayPrice().doubleValue()));
            map.put("payPriceFen", MathUtil.getDoubleUp(order.getPayPrice().doubleValue() * 100));

            int mer_id = order.getMerId();

            map.put("isHasVip", 0);
            //订单类型  0 - 平台商品类  1 - 设备上的商品类  2 - 线下商家活动  3 - 商家优惠券 4 - 团购类  5 - 秒杀类  6 - 商家点餐类
            //如果是团购类  查询出来当前参团人员信息
            if(order.getOrderType() == 4){

                List<String> templateIds = new ArrayList<>();
                Integer[] types = { 25, 26 , 27 };//团购订阅消息类型
                QueryWrapper<WxTemplate> qwTemplate = new QueryWrapper<>();
                qwTemplate.in("template_type", Arrays.asList(types));
                List<WxTemplate> templates = wxTemplateService.list(qwTemplate);
                if(CollUtil.isNotEmpty(templates)){
                    for (WxTemplate temp: templates){
                        templateIds.add(temp.getTemplateId());
                    }
                }
                map.put("templateIds",templateIds);
            } else if(order.getOrderType() == 6){

                map.put("mer_name", "");
                Mer mer = merService.findById(mer_id);
                if(mer != null){
                    map.put("mer_name", mer.getShopName());
                }
            }
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"获取成功",map),true,false);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
            System.out.println(""+e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    /**
     *  订单详情
     * @param
     * @throws Exception
     */
    @PostMapping(value="/detail")
    public JSONObject detail(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int order_id = jsonRequest.containsKey("order_id") ? jsonRequest.getInt("order_id") : 0;
            int mer_id = jsonRequest.containsKey("mer_id") ? jsonRequest.getInt("mer_id") : 0;
            int address_id = jsonRequest.containsKey("address_id") ? jsonRequest.getInt("address_id") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            ProductOrder order = productOrderService.getOrderDetail(order_id);
            if(order == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前订单不存在"),true,true);
            }else{
                if(mer_id > 0){
                    MerUser merUser = merUserService.getMerByUser(user_id,mer_id);
                    if(merUser == null){
                        return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前订单不属于您的商家"),true,true);
                    }
                }else{
                    if(order.getUserId() != user_id){
                        return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前订单不属于您"),true,true);
                    }
                }
            }
            map.put("order",order);

            UserAddress userAddress = userAddressService.selectDefaultAddress(user_id);
            if(address_id > 0){
                userAddress = userAddressService.getById(address_id);
            }
            map.put("address",userAddress);
            if(userAddress!=null){
                map.put("is_has_address",1);
            }else{
                map.put("is_has_address",0);
            }

            map.put("is_in_poly", 0);
            if(order.getOrderType() == 7){
                Mer mer = merService.findById(order.getMerId());
                if(mer!= null){
                    boolean blIsInPoly = merService.isInPoly(mer, userAddress);
                    map.put("is_in_poly", blIsInPoly? 1: 0);
                }
            }

            //订单类型  0 - 平台商品类  1 - 设备上的商品类  2 - 线下商家活动  3 - 商家优惠券 4 - 团购类  5 - 秒杀类  6 - 商家点餐类
            //如果是团购类  查询出来当前参团人员信息
            if(order.getOrderType() == 4){

                List<String> templateIds = new ArrayList<>();
                Integer[] types = { 25, 26 , 27 };//团购订阅消息类型
                QueryWrapper<WxTemplate> qwTemplate = new QueryWrapper<>();
                qwTemplate.in("template_type", Arrays.asList(types));
                List<WxTemplate> templates = wxTemplateService.list(qwTemplate);
                if(CollUtil.isNotEmpty(templates)){
                    for (WxTemplate temp: templates){
                        templateIds.add(temp.getTemplateId());
                    }
                }
                map.put("templateIds",templateIds);
            } else if(order.getOrderType() == 6){

                map.put("mer_name", "");
                Mer mer = merService.findById(mer_id);
                if(mer != null){
                    map.put("mer_name", mer.getShopName());
                }
            }

            map.put("goldenMoney", 0);
            SplitAccount splitAccount = splitAccountService.getAccountByUserId(user_id,4,user_id);
            if(splitAccount!=null){
                map.put("goldenMoney",splitAccount.getGoldenMoney());
            }

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"获取成功",map),true,false);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
            System.out.println(""+e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 订单详情
     * @param
     * @throws Exception
     */
    @PostMapping(value="/orderInfo")
    public JSONObject orderInfo(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            long info_id = jsonRequest.containsKey("info_id") ? jsonRequest.getLong("info_id") : 0;
            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            ProductOrderInfo orderInfo = productOrderInfoService.findById(info_id);
            if(orderInfo == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前订单不存在"),true,true);
            }

            if(StrUtil.isNotEmpty(orderInfo.getQrCode())){
                orderInfo.setQrCode(imgPrefix + orderInfo.getQrCode());
            }

            if(StrUtil.isEmpty(orderInfo.getSkuName())){
                ProductAttrValue attrValue = productAttrValueService.findById(orderInfo.getSkuId());
                if(attrValue!=null){
                    orderInfo.setSkuName(attrValue.getSku());
                }
            }

            ProductOrder order = productOrderService.findById(orderInfo.getOrderId());
            if(order != null){
                map.put("nickName", EmojiParser.parseToUnicode(order.getRealName()));
            }
            Product product = productService.getProductInfoById(orderInfo.getProductId(), 0);
            if (product != null) {
                orderInfo.setProductName(product.getStoreName());
                orderInfo.setImgUrl(imgPrefix + product.getImage());
            }
            map.put("order",order);
            map.put("orderInfo",orderInfo);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"获取成功",map),true,false);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
            System.out.println(""+e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 订单详情
     * @param
     * @throws Exception
     */
    @PostMapping(value="/info/detail")
    public JSONObject infoDetail(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            long info_id = jsonRequest.containsKey("info_id") ? jsonRequest.getLong("info_id") : 0;
            int reset_qr_code = jsonRequest.containsKey("reset_qr_code") ? jsonRequest.getInt("reset_qr_code") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            ProductOrderInfo orderInfo = productOrderInfoService.getInfoQrCode(info_id, reset_qr_code);
            if(orderInfo == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前订单不存在"),true,true);
            }

            if(StrUtil.isNotEmpty(orderInfo.getQrCode())){
                orderInfo.setQrCode(imgPrefix + orderInfo.getQrCode());
            }

            if(StrUtil.isEmpty(orderInfo.getSkuName())) {
                ProductAttrValue attrValue = productAttrValueService.findById(orderInfo.getSkuId());
                if (attrValue != null) {
                    orderInfo.setSkuName(attrValue.getSku());
                }
            }

            map.put("nickName", EmojiParser.parseToUnicode(user.getNickName()));
            Product product = productService.getProductInfoById(orderInfo.getProductId(), 0);
            if (product != null) {
                orderInfo.setProductName(product.getStoreName());
                orderInfo.setImgUrl(product.getImage());
            }
            map.put("orderInfo",orderInfo);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"获取成功",map),true,false);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
            System.out.println(""+e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 删除订单明细
     * @param
     * @throws Exception
     */
    @PostMapping(value="/info/delete")
    public JSONObject orderInfoDelete(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            long info_id = jsonRequest.containsKey("info_id") ? jsonRequest.getLong("info_id") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            try{
                int ret = productOrderInfoService.deleteInfo(info_id);
                if(ret > 0){
                    result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"获取成功"),true,true);
                } else if(ret == -1){
                    result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前状态不能删除"),true,true);
                } else if(ret == -2){
                    result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"剩余一个商品，不能再删除"),true,true);
                } else{
                    result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"删除失败"),true,true);
                }
            }catch (Exception e){
                e.printStackTrace();
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"删除失败"),true,true);
            }
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
            System.out.println(""+e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 添加订单明细
     * @param
     * @throws Exception
     */
    @PostMapping(value="/info/add")
    public JSONObject orderInfoAdd(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            long order_id = jsonRequest.containsKey("order_id") ? jsonRequest.getLong("order_id") : 0;
            long product_id = jsonRequest.containsKey("product_id") ? jsonRequest.getLong("product_id") : 0;
            int attr_value_id = jsonRequest.containsKey("attr_value_id") ? jsonRequest.getInt("attr_value_id") : 0;
            int count = jsonRequest.containsKey("count") ? jsonRequest.getInt("count") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            ProductOrder order = productOrderService.findById(order_id);
            if(order == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该订单不存在" ),true,true);
            }

            Product product = productService.findById(product_id);
            if(product == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该商品不存在"),true,true);
            }

            ProductAttrValue attrValue = productAttrValueService.findById(attr_value_id);
            if(attrValue == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该商品规格不存在"),true,true);
            }

            try{
                Map<String,Object> map = productOrderInfoService.addInfo(user, order, product, attrValue, count);
                int ret = Integer.parseInt(map.get("ret").toString());
                if(ret > 0){
                    result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"添加成功",map),true,false);
                } else{
                    result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"添加失败"),true,true);
                }
            }catch (Exception e){
                e.printStackTrace();
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"添加失败"),true,true);
            }
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
            System.out.println(""+e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 添加订单明细
     * @param
     * @throws Exception
     */
    @PostMapping(value="/info/update")
    public JSONObject orderInfoUpdate(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            long order_id = jsonRequest.containsKey("order_id") ? jsonRequest.getLong("order_id") : 0;
            long info_id = jsonRequest.containsKey("order_id") ? jsonRequest.getLong("info_id") : 0;
            int count = jsonRequest.containsKey("count") ? jsonRequest.getInt("count") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            ProductOrder order = productOrderService.findById(order_id);
            if(order == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该订单不存在" ),true,true);
            }

            ProductOrderInfo orderInfo = productOrderInfoService.findById(info_id);
            if(orderInfo == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该信息不存在"),true,true);
            }

            try{
                Map<String,Object> map = productOrderInfoService.updateInfo(order, orderInfo, count);
                int ret = Integer.parseInt(map.get("ret").toString());
                if(ret > 0){
                    result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"添加成功", map),true,false);
                } else{
                    result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"添加失败"),true,true);
                }
            }catch (Exception e){
                e.printStackTrace();
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"添加失败"),true,true);
            }
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
            System.out.println(""+e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    /** 通过购物车生成订单
     * @param
     * @throws Exception
     */
    @PostMapping(value="/addOrderByCart")
    public JSONObject addOrderByCart(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "product/order/addOrder 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            //订单类型  0 - 平台商品类  1 - 设备上的商品类  2 - 线下商家活动  3 - 商家优惠券 4 - 团购类  5 - 秒杀类  6 - 商家点餐类
            int order_type = jsonRequest.containsKey("order_type") ? jsonRequest.getInt("order_type") : 0;
            String remark = jsonRequest.containsKey("remark") ? jsonRequest.get("remark").toString() : "";
            int address_id = jsonRequest.containsKey("address_id") ? jsonRequest.getInt("address_id") : 0;
            String platform = jsonRequest.containsKey("platform") ? jsonRequest.getStr("platform") : "wxmini";

            double allPrice = 0;
            User user = userService.findById(user_id);
            if(user == null) {
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }
            //购物车
            List<ProductCart> cars = productCartService.selectByUserId(user_id,1);
            if(cars != null && cars.size() > 0) {
                for(ProductCart car : cars) {
                    allPrice += car.getSinglePrice().doubleValue() * car.getCartNum();
                }
            }else {
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您没有选中任何商品，无法生成订单"),true,true);
            }
            UserAddress userAddress = null;
            if(order_type != 6){
                userAddress = userAddressService.findById(address_id);
                if(userAddress == null) {
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"请选择有效地址"),true,true);
                }
            }

            String payNo = productOrderService.addNormalOrder(user,userAddress,allPrice,order_type,remark,platform);
            if(payNo!=null){
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"添加成功",payNo),true,false);
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"添加失败"),true,true);
            }
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
            System.out.println(""+e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 商品的立即购买
     * @param
     * @throws Exception
     */
    @PostMapping(value="/addOrderBuyNow")
    public JSONObject addOrderBuyNow(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "product/order/addOrderBuyNow 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int count = jsonRequest.containsKey("count") ? jsonRequest.getInt("count") : 0;
            int attr_value_id = jsonRequest.containsKey("attr_value_id") ? jsonRequest.getInt("attr_value_id") : 0;
            //订单类型  0 - 平台商品类  1 - 设备上的商品类  2 - 线下商家活动  3 - 商家优惠券 4 - 团购类
            int order_type = jsonRequest.containsKey("order_type") ? jsonRequest.getInt("order_type") : 0;
            String remark = jsonRequest.containsKey("remark") ? jsonRequest.getStr("remark") : "";
            String platform = jsonRequest.containsKey("platform") ? jsonRequest.getStr("platform") : "wxmini";

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            ProductAttrValue attrValue = productAttrValueService.findById(attr_value_id);
            if(attrValue != null){
                Product product = productService.getProductInfoById(attrValue.getProductId(), 0);
                if (product != null) {
                    try {
                        long order_id = productOrderService.buyNow(user, null, order_type, count, attrValue,remark,platform);
                        if (order_id > 0) {
                            return Tools.getJson(new GsonResultBean<>(ResponseCode.OK, "成功", order_id), true, false);
                        } else {
                            return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "失败"), true, true);
                        }
                    } catch (Exception ex) {
                        return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "失败"), true, true);
                    }
                } else {
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "该商品不存在"), true, true);
                }
            }else{
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该商品规格不存在"),true,true);
            }
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
            System.out.println(""+e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 商品的立即购买
     * @param
     * @throws Exception
     */
    @PostMapping(value="/addOrderBuyNowBg")
    public JSONObject addOrderBuyNowBg(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "product/order/addOrderBuyNow 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int count = jsonRequest.containsKey("count") ? jsonRequest.getInt("count") : 0;
            int attr_value_id = jsonRequest.containsKey("attr_value_id") ? jsonRequest.getInt("attr_value_id") : 0;
            //订单类型  0 - 平台商品类  1 - 设备上的商品类  2 - 线下商家活动  3 - 商家优惠券 4 - 团购类
            int order_type = jsonRequest.containsKey("order_type") ? jsonRequest.getInt("order_type") : 0;
            String remark = jsonRequest.containsKey("remark") ? jsonRequest.getStr("remark") : "";
            String platform = jsonRequest.containsKey("platform") ? jsonRequest.getStr("platform") : "wxmini";

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            ProductAttrValue attrValue = productAttrValueService.findById(attr_value_id);
            if(attrValue != null){
                Product product = productService.getProductInfoById(attrValue.getProductId(), 0);
                if (product != null) {
                    try {
                        long order_id = productOrderService.buyNowBg(user, null, order_type, count, attrValue,remark,platform);
                        if (order_id > 0) {
                            return Tools.getJson(new GsonResultBean<>(ResponseCode.OK, "成功", order_id), true, false);
                        } else {
                            return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "失败"), true, true);
                        }
                    } catch (Exception ex) {
                        return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "失败"), true, true);
                    }
                } else {
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "该商品不存在"), true, true);
                }
            }else{
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该商品规格不存在"),true,true);
            }
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
            System.out.println(""+e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 取消订单
     * @param
     * @throws Exception
     */
    @PostMapping(value="/cancelOrder")
    public JSONObject cancelOrder(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "product/order/cancelOrder 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int order_id = jsonRequest.containsKey("order_id") ? jsonRequest.getInt("order_id") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }
            ////订单状态 0 - 未支付   1 - 已支付，待发货  2 - 已发货， 待收货  3 - 已收货，待评价 4 - 已评价  5 - 订单取消  6 - 已申请退货  7 - 同意退货  8 - 退货完成 9 - 拒绝退货
            ProductOrder order = productOrderService.findById(order_id);
            if(order == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前订单不存在"),true,true);
            }else if(order.getUserId() != user_id){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前订单不属于您"),true,true);
            }

            //订单状态订单状态 0 - 未支付   1 - 支付中  2 - 已支付（待核销）  3 - 已核销
            // 4 - 已评价  5 - 订单取消  6 - 发起退货  7 - 同意退货  8 - 退货完成  9 - 拒绝退货
            if(order.getStatus() == 0 || order.getStatus() == 1){
                productOrderService.updateOrderState(order,5);
                return Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"订单取消成功"),true,true);
            }else if(order.getStatus() == 6){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前订单已取消"),true,true);
            }else{
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前状态不能取消"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
            System.out.println(""+e.getMessage());
        }
        return result;
    }

    /**
     *  退货申请
     * @param
     * @throws Exception
     */
    @PostMapping(value="/refundReg")
    public JSONObject refundReg(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "product/order/refundReg 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int order_id = jsonRequest.containsKey("order_id") ? jsonRequest.getInt("order_id") : 0;
            String reason = jsonRequest.containsKey("reason") ? jsonRequest.getStr("reason") : "";

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }
            ////订单状态 0 - 未支付   1 - 已支付，待发货  2 - 已发货， 待收货  3 - 已收货，待评价
            // 4 - 已评价  5 - 订单取消  6 - 已申请退货  7 - 同意退货  8 - 退货完成 9 - 拒绝退货
            ProductOrder order = productOrderService.findById(order_id);
            if(order == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前订单不存在"),true,true);
            }else if(order.getUserId() != user_id){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前订单不属于您"),true,true);
            }

            //订单状态 0 - 未支付   1 - 支付中  2 - 已支付（待核销）  3 - 已核销
            // 4 - 已评价  5 - 订单取消  6 - 发起退货  7 - 同意退货  8 - 退货完成  9 - 拒绝退货
            if(order.getStatus() == 2){
                //refund_reason_wap_explain
                order.setRefundReasonWapExplain(reason);//退货理由说明
                productOrderService.updateOrderState(order,6);
                return Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"退款申请成功"),true,true);
            }else if(order.getStatus() == 6){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前订单已发起退款"),true,true);
            }else{
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前状态不能退款"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
            System.out.println(""+e.getMessage());
        }
        return result;
    }

    /**
     *  拒绝退货申请
     * @param
     * @throws Exception
     */
    @PostMapping(value="/refuseRefund")
    public JSONObject refuseRefund(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "product/order/refuseRefund 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int order_id = jsonRequest.containsKey("order_id") ? jsonRequest.getInt("order_id") : 0;
            String reason = jsonRequest.containsKey("reason") ? jsonRequest.getStr("reason") : "";

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            ////订单状态 0 - 未支付   1 - 已支付，待发货  2 - 已发货， 待收货  3 - 已收货，待评价
            // 4 - 已评价  5 - 订单取消  6 - 已申请退货  7 - 同意退货  8 - 退货完成 9 - 拒绝退货
            ProductOrder order = productOrderService.findById(order_id);
            if(order == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"订单不存在"),true,true);
            }

            MerUser merUser = merUserService.getMerByUser(user_id,order.getMerId());
            if(merUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"没有操作权限"),true,true);
            }

            if(merUser.getUserId() != user_id){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前订单不属于您的商户"),true,true);
            }

            //订单状态 0 - 未支付   1 - 支付中  2 - 已支付（待核销）  3 - 已核销
            // 4 - 已评价  5 - 订单取消  6 - 发起退货  7 - 同意退货  8 - 退货完成  9 - 拒绝退货
            if(order.getStatus() == 6){
                order.setRefundReason(reason);//拒绝理由
                productOrderService.updateOrderState(order,9);
                return Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"退款申请拒绝成功"),true,true);
            }else{
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前状态不能操作"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
            System.out.println(""+e.getMessage());
        }
        return result;
    }

    /**
     *  重新生成核销二维码
     * @param
     * @throws Exception
     */
    @PostMapping(value="/resetOrderInfoQrCode")
    public JSONObject resetOrderInfoQrCode(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "product/order/resetOrderInfoQrCode 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            long info_id = jsonRequest.containsKey("info_id") ? jsonRequest.getLong("info_id") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            ProductOrderInfo orderInfo = productOrderInfoService.findById(info_id);
            if(orderInfo==null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前订单不存在"),true,true);
            }
            try{
                Date date = DateUtil.getAfterSecondsByOld(new Date(),60);
                String time = date.getTime()+"";
                String qrcode = "";
                String fileName = "order_info_qr_" + orderInfo.getId() + ".jpg";
                String content = "{\"qrtype\":\"orderInfo\",\"id\":"+orderInfo.getId()+",\"expire_time\":" + time + "}";
                Aes aes = new Aes();
                int upload_type = OssUtil.TYPE_ORDER_INFO_VERIFYCODE_IMGS;
                content = aes.encrypt(content);
                System.out.println("content:  "+ content);
                String img_key = "";
                img_key = OssUtil.getUploadPrefix(upload_type) + fileName;
                boolean bl = FileUtil.deleteFile(uploadPath + img_key);
                if(bl){
                    System.out.println("删除成功："+ uploadPath + img_key);
                }else{
                    System.out.println("删除失败："+ uploadPath + img_key);
                }
                QRCodeUtilEx.createQrCodeImg(content, "核销码：" + orderInfo.getVerifyCode(), null, uploadPath + img_key, true,fileName,upload_type);
                qrcode = img_key;
                orderInfo.setQrCode(qrcode);
                orderInfo.setCodeExpireTime(new Date());
                productOrderInfoService.updateById(orderInfo);
            }catch (Exception ex){
                ex.printStackTrace();
            }
            orderInfo.setQrCode(imgPrefix + orderInfo.getQrCode());
            map.put("orderInfo",orderInfo);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"获取成功",map),true,false);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
            System.out.println(""+e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 订单支付详情
     * @param
     * @throws Exception
     */
    @PostMapping(value="/detail/pay")
    public JSONObject detailPay(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "product/order/detail/pay 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int order_id = jsonRequest.containsKey("order_id") ? jsonRequest.getInt("order_id") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            ProductOrder order = productOrderService.findById(order_id);
            if(order==null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前订单不存在"),true,true);
            }else if(order.getUserId() != user_id){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前订单不属于您"),true,true);
            }
            map.put("allprice",order.getPayPrice());
            map.put("order_id",order_id);
            map.put("order_type",order.getOrderType());
            map.put("order_state",order.getStatus());
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"获取成功",map),true,false);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
            System.out.println(""+e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 获取的支付参数
     * @param
     * @throws Exception
     */
    @PostMapping(value="/payInfo")
    public JSONObject payInfo(@RequestBody String requestParam, HttpServletRequest request) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "product/order/payInfo 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            long order_id = jsonRequest.containsKey("order_id") ? jsonRequest.getLong("order_id") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }
            ////订单状态 0 - 未支付   1 - 已支付，待发货  2 - 已发货， 待收货  3 - 已收货，待评价 4 - 已评价  5 - 订单取消  6 - 已申请退货  7 - 同意退货  8 - 退货完成 9 - 拒绝退货
            ProductOrder order = productOrderService.findById(order_id);
            if(order == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前订单不存在"),true,true);
            }else if(order.getUserId() != user_id){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前订单不属于您"),true,true);
            }
            if(order.getStatus() == 1){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前订单已支付!"),true,true);
            }else if(order.getStatus() > 1){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前订单不能支付"),true,true);
            }


            WxAppPay wxAppPay = null;//new WxAppPay();
            String wxpayinfo = wxAppPay.weiXinPrePay(order.getOrderNo(),order.getPayPrice(),"购买商品",request.getRemoteAddr(),user.getOpenId(),"NORMAL");
            JSONObject jsonObject = JSONUtil.parseObj(wxpayinfo);
            map.put("wxpayinfo",jsonObject);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"获取成功",wxpayinfo),true,false);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
            System.out.println(""+e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 确认收货
     * @param
     * @throws Exception
     */
    @PostMapping(value="/confirmReceipt")
    public JSONObject confirmReceipt(@RequestBody String requestParam, HttpServletRequest request) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "product/order/confirmReceipt 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int order_id = jsonRequest.containsKey("order_id") ? jsonRequest.getInt("order_id") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }
            ////订单状态 0 - 未支付   1 - 已支付，待发货  2 - 已发货， 待收货  3 - 已收货，待评价 4 - 已评价  5 - 订单取消  6 - 已申请退货  7 - 同意退货  8 - 退货完成 9 - 拒绝退货
            ProductOrder order = productOrderService.findById(order_id);
            if(order == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前订单不存在"),true,true);
            }else if(order.getUserId() != user_id){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前订单不属于您"),true,true);
            }

            if(order.getStatus() == 0){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前订单未支付!"),true,true);
            }else if(order.getStatus() == 1){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前订单未发货"),true,true);
            }else if(order.getStatus() == 2){
                //订单状态订单状态 0 - 未支付   1 - 支付中  2 - 已支付（待核销）  3 - 已核销
                // 4 - 已评价  5 - 订单取消  6 - 发起退货  7 - 同意退货  8 - 退货完成  9 - 拒绝退货
                productOrderService.updateOrderState(order,3);
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功"),true,true);
                //todo  需发送公众号推送消息  确认收货的消息
            }else if(order.getStatus() == 3){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前订单已确认收货"),true,true);
            }else if(order.getStatus() == 4){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前订单已取消"),true,true);
            }else if(order.getStatus() == 5){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前订单已取消"),true,true);
            }else if(order.getStatus() == 6){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前订单已申请退货"),true,true);
            }else{
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前订单无需确认收货"),true,true);
            }
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
            System.out.println(""+e.getMessage());
            e.printStackTrace();
        }
        return result;
    }


    /**
     *  退货申请上传图片
     * @param
     * @throws Exception
     */
    @PostMapping(value="/uploadImgRefundOrder")
    public JSONObject uploadImgRefundOrder(@RequestParam("order_id") int order_id, HttpServletRequest request) throws Exception{
        JSONObject result = null;
        try{
            ProductOrder order = productOrderService.findById(order_id);
            if(order == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "订单不存在"), true, true);
            }
            // 创建一个通用的多部分解析器.
            CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
            // 设置编码
            commonsMultipartResolver.setDefaultEncoding("utf-8");
            // 判断是否有文件上传
            if (commonsMultipartResolver.isMultipart(request)) {//有文件上传
                //将request变成多部分request
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
                //获取multiRequest 中所有的文件名
                Iterator<String> iter = multiRequest.getFileNames();
                if (iter.hasNext()) {
                    Map<String, MultipartFile> maps = multiRequest.getFileMap();
                    int index = 0;
                    for(String key : maps.keySet()) {
                        MultipartFile certurl = maps.get(key);
                        if (!certurl.isEmpty()) {
                            String prefix = certurl.getOriginalFilename().substring(certurl.getOriginalFilename().lastIndexOf(".") + 1);
                            if ("jpeg".equals(prefix) || "jpg".equals(prefix) || "png".equals(prefix)) {
                                String fileName = "refund_img_" + new Date().getTime() + "." + prefix;// user_photo.getOriginalFilename();
                                try {
                                    byte[] byteImg = certurl.getBytes();
                                    if (byteImg != null) {
                                        //上传头像到OSS
                                        int upload_type = OssUtil.TYPE_ORDER_REFUND_IMGS;
                                        String img_key = OssUtil.getUploadPrefix(upload_type) + fileName;

                                        String filePath = uploadPath + img_key;
                                        FileOutputStream out = new FileOutputStream(filePath);
                                        out.write(certurl.getBytes());
                                        out.flush();
                                        out.close();


                                        ImagesFiler.imageResize(filePath,filePath);
//                                        OssUtil.upload(certurl.getInputStream(),fileName,upload_type);

                                        ProductOrderRefundImg img = new ProductOrderRefundImg();
                                        img.setImgUrl(img_key);
                                        img.setOrderId(order_id);
                                        img.setSort(index);
                                        orderRefundImgService.save(img);
                                        index++;
                                    }
                                } catch (IOException e) {
                                    e.printStackTrace();
                                    result = Tools.getJson(new GsonResultBean<>(-4, "系统异常"), true, true);
                                }
                            }
                        }
                    }
                }
            }
            return Tools.getJson(new GsonResultBean<>(ResponseCode.OK, "上传图片成功"), true, true);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
            System.out.println(""+e.getMessage());
            e.printStackTrace();
        }
        return result;
    }
}
